package com.gyj.user.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Gao on 2018/5/23.
 */
public class DateUtils {
    /**
     * 将字符串时间转为date类型
     */
    public static Date stringDateFormat(String strdate, String dateformat) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat(dateformat);
            Date parse = formatter.parse(strdate);
            return parse;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取当前时间到第二天0点的时间
     */
    public static long getNowToNextDayTime() {
        final Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) + 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        long diff = cal.getTimeInMillis() - System.currentTimeMillis();
        return diff;
    }

    /**
     * 获取当前时间的最近天数
     *
     * @param days
     * @throws ParseException
     */
    public static Date getStatetime(int days) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDDhhmmss");

        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, -days);
        java.util.Date monday = c.getTime();
        return monday;
    }

    /**
     * 最近几个月的时间
     * @param months
     * @throws ParseException
     */
    public static String getMonthTime(int months) throws ParseException {

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -months);  //设置为前month个月
        Date time = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String beforeTime = sdf.format(time);

        return beforeTime;
    }

    /**
     * 转换成hbase使用格式,入参：2017-01-01 12:12:12
     */
    public static String hbaseFormat(String dateStr) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date parse = formatter.parse(dateStr);
        formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        return formatter.format(parse);
    }
}
